﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using DHM.IRepository;
using DHM.Model;
using SqlSugar;
using SqlSugar.IOC;
namespace DHM.Repository
{
    public class BaseRepository<T> : SimpleClient<T>, IBaseRepository<T> where T : class, new()
    {
        public BaseRepository(ISqlSugarClient context = null) : base(context)
        {
            base.Context = DbScoped.Sugar;

            //base.Context.DbMaintenance.CreateDatabase();

            //base.Context.CodeFirst.InitTables(
            //    typeof(UserComment),
            //    typeof(UserLikes),
            //    typeof(UserViews)
            //    );
        }

        public virtual async Task<bool> AddAsync(T entity)
        {
            return await base.InsertAsync(entity);
        }

        public virtual async Task<T> FindAsync(int id)
        {
            return await base.GetByIdAsync(id);
        }

        public virtual async Task<T> FindAsync(Expression<Func<T, bool>> func)
        {
            return await base.GetSingleAsync(func);
        }

        public virtual async Task<List<T>> QueryAsync()
        {
            return await base.GetListAsync();
        }

        public virtual async Task<List<T>> QueryAsync(Expression<Func<T, bool>> func)
        {
            return await base.GetListAsync(func);
        }

        public virtual async Task<List<T>> QueryAsync(int page, int size, RefAsync<int> total)
        {
            return await base.Context.Queryable<T>().ToPageListAsync(page, size, total);
        }

        public virtual async Task<List<T>> QueryAsync(Expression<Func<T, bool>> func1,int page, int size, RefAsync<int> total)
        {
            return await base.Context.Queryable<T>().Where(func1).ToPageListAsync(page, size, total);
        }

        public virtual async Task<List<T>> QueryAsyncOrder(Expression<Func<T, bool>> func, Expression<Func<T, object>> func2,OrderByType ordertype,int page, int size,
            RefAsync<int> total)
        {
            return await base.Context.Queryable<T>().Where(func).OrderBy(func2, ordertype)
                .ToPageListAsync(page, size, total);
        }

        public async Task<int> GetModuleCount(Expression<Func<T, bool>> func)
        {
            return await base.Context.Queryable<T>().CountAsync(func);
        }
    }
}
